package com.pair.micro.common.mybatis.typehandler;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/** 存储到数据库, 将JSONArray转换成字符串; 从数据库获取数据, 将字符串转为JSONArray. */
@MappedTypes({JSONArray.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class JSONArrayTypeHandler extends BaseTypeHandler<JSONArray> {

  @Override
  public void setNonNullParameter(
      PreparedStatement ps, int i, JSONArray parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, JSONUtil.toJsonStr(parameter));
  }

  @Override
  public JSONArray getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
    return JSONUtil.parseArray(resultSet.getString(columnName)).toBean(JSONArray.class);
  }

  @Override
  public JSONArray getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
    return JSONUtil.parseArray(resultSet.getString(columnIndex)).toBean(JSONArray.class);
  }

  @Override
  public JSONArray getNullableResult(CallableStatement callableStatement, int columnIndex)
      throws SQLException {
    return JSONUtil.parseArray(callableStatement.getString(columnIndex)).toBean(JSONArray.class);
  }
}
